package com.atguigu.realtime.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.bean.TestExamPaperBean;
import com.atguigu.realtime.bean.TestExamPaperScoreStageBean;
import com.atguigu.realtime.utils.*;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class DwsTestPaperScorestageCountWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //todo 3 读取 kafka 中 dwd_test_exam 表
        String topicName = "dwd_test_exam";
        String groupID = "Dws_test_paper_scorestage_count_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupID));

        //todo 4 转换结构
        SingleOutputStreamOperator<TestExamPaperScoreStageBean> mapStream = streamSource.map(new MapFunction<String, TestExamPaperScoreStageBean>() {
            @Override
            public TestExamPaperScoreStageBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                TestExamPaperScoreStageBean bean = TestExamPaperScoreStageBean.builder()
                        .paperId(jsonObject.getString("paper_id"))
                        .userId(jsonObject.getString("user_id"))
                        .ts(DateFormatUtil.toTs(jsonObject.getString("create_time"), true))
                        .uidSet(new HashSet<>(Collections.singleton(jsonObject.getString("user_id"))))
                        .build();
                String level = "";
                if ("不及格".equals(jsonObject.getString("score_level"))) {
                    level = "0-60";
                } else if ("及格".equals(jsonObject.getString("score_level"))) {
                    level = "60-70";
                } else if ("良好".equals(jsonObject.getString("score_level"))) {
                    level = "70-80";
                } else {
                    level = "80-100";
                }

                bean.setScoreLevel(level);

                return bean;


            }
        });

        //todo 5 开窗聚合
        //水位线
        SingleOutputStreamOperator<TestExamPaperScoreStageBean> watermarks = mapStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<TestExamPaperScoreStageBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<TestExamPaperScoreStageBean>() {
                    @Override
                    public long extractTimestamp(TestExamPaperScoreStageBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));
        //分组
        KeyedStream<TestExamPaperScoreStageBean, String> keyedStream = watermarks.keyBy(new KeySelector<TestExamPaperScoreStageBean, String>() {
            @Override
            public String getKey(TestExamPaperScoreStageBean value) throws Exception {
                return (value.getPaperId() + value.getScoreLevel());
            }
        });
        //开窗
        WindowedStream<TestExamPaperScoreStageBean, String, TimeWindow> windowedStream = keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(10L)));
        //聚合
        SingleOutputStreamOperator<TestExamPaperScoreStageBean> reduceStream = windowedStream.reduce(new ReduceFunction<TestExamPaperScoreStageBean>() {
            @Override
            public TestExamPaperScoreStageBean reduce(TestExamPaperScoreStageBean value1, TestExamPaperScoreStageBean value2) throws Exception {
                value1.getUidSet().addAll(value2.getUidSet());
                return value1;
            }
        }, new WindowFunction<TestExamPaperScoreStageBean, TestExamPaperScoreStageBean, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow window, Iterable<TestExamPaperScoreStageBean> input, Collector<TestExamPaperScoreStageBean> out) throws Exception {
                TestExamPaperScoreStageBean bean = input.iterator().next();
                bean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                bean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                bean.setTs(System.currentTimeMillis());
                bean.setNumber(bean.getUidSet().size());

                out.collect(bean);
            }
        });

        //todo 6 关联dim表
        //dim_test_paper
        SingleOutputStreamOperator<TestExamPaperScoreStageBean> resultStream = reduceStream.map(new RichMapFunction<TestExamPaperScoreStageBean, TestExamPaperScoreStageBean>() {
            DruidDataSource dataSource = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                dataSource = DruidPhoenixDSUtil.getDataSource();
            }

            @Override
            public TestExamPaperScoreStageBean map(TestExamPaperScoreStageBean value) throws Exception {
                DruidPooledConnection connection = dataSource.getConnection();

                //关联试卷表
                List<JSONObject> testPaper = DimUtil.getDimInfo(connection, "DIM_TEST_PAPER", value.getPaperId());
                if (testPaper.size()>0) {
                    JSONObject tp = testPaper.get(0);
                    value.setPaperTitle(tp.getString("paperTitle"));

                }return value;
            }
        });

        reduceStream.print();
        //写入到click house
        resultStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into Dws_test_paper_scorestage_count_window values(?,?,?,?,?,?,?)"));


        //执行
        env.execute();

    }
}
